import 'package:flutter/material.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:oktoast/oktoast.dart';

class IDValidityPicker extends StatefulWidget {
  final List<String> validityOptions; // 有效期选项列表
  final String? initialValidity;    // 初始选中的有效期
  final String? initialValidityCode; // 初始选中的有效期代码（如 "long" 表示长期）
  const IDValidityPicker({
    super.key,
    required this.validityOptions,
    this.initialValidity,
    this.initialValidityCode,
  });

  @override
  State<IDValidityPicker> createState() => _IDValidityPickerState();
}

class _IDValidityPickerState extends State<IDValidityPicker> {
  late List<String> filteredOptions;
  late String? selectedValidity;
  late String? selectedCode;
  final TextEditingController searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    filteredOptions = widget.validityOptions;
    selectedValidity = widget.initialValidity;
    selectedCode = widget.initialValidityCode;
    searchController.addListener(() {
      final query = searchController.text.toLowerCase();
      setState(() {
        if (query.isEmpty) {
          filteredOptions = widget.validityOptions;
        } else {
          filteredOptions =
              widget.validityOptions
                  .where((option) => option.toLowerCase().contains(query))
                  .toList();
        }
      });
    });
  }

  @override
  void dispose() {
    searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.8,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          // 标题和关闭按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '选择证件有效期',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 搜索框（可选，根据需求保留或移除）
          TextField(
            controller: searchController,
            decoration: InputDecoration(
              hintText: '搜索有效期选项...',
              prefixIcon: const Icon(Icons.search, color: Colors.grey),
              suffixIcon: searchController.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear, color: Colors.grey),
                      onPressed: () => {searchController.clear()},
                    )
                  : null,
              filled: true,
              fillColor: Colors.grey[50],
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide.none,
              ),
              contentPadding: const EdgeInsets.symmetric(
                vertical: 16,
                horizontal: 20,
              ),
            ),
          ),

          const SizedBox(height: 16),

          // 有效期列表
          Expanded(
            child: ListView.separated(
              itemCount: filteredOptions.length,
              separatorBuilder: (context, index) => const Divider(height: 1, indent: 16),
              itemBuilder: (context, index) {
                final option = filteredOptions[index];
                return ListTile(
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                  title: Text(
                    option,
                    style: const TextStyle(fontSize: 16),
                  ),
                  trailing: selectedValidity == option
                      ? const Icon(Icons.check, color: Colors.blue)
                      : null,
                  onTap: () {
                    setState(() {
                      selectedValidity = option;
                      selectedCode = option == '长期有效' ? 'long' : option.split(' ')[0];
                    });
                  },
                );
              },
            ),
          ),

          const SizedBox(height: 20),
          // 确定按钮
          Center(
            child: ButtonWidget(
              label: "确定",
              width: 322, // 注意：322.px 应该改为 322，或者使用 MediaQuery 获取宽度
              height: 54,
              fontSize: 18.px,
              imageBg: 'static/images/btm.png',
              contentType: ContentType.other,
              onPressed: () {
                if (selectedValidity == null || selectedCode == null) {
                  showToast('请选择证件有效期');
                } else {
                  Navigator.pop(context, {
                    'selectedValidity': selectedValidity,
                    'selectedCode': selectedCode,
                  });
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}
